using System;
using System.Linq;
using System.Web;
using Peak.Core;
using SharpArch.Core.PersistenceSupport;
using Peak.Core.DataInterfaces;

namespace Peak.Web.Controllers.Services
{
  public class SessionService : ISessionService
  {
    public const string CurrentProjectId = "CurrentProjectId";    
    private const string BackLinkConst = "BackLink";

    private readonly IRepository<Project> _projectRepository;    
    private readonly IUserRepository _userRepository;

    public SessionService(
      IRepository<Project> projectRepository,             
      IUserRepository userRepository)
    {
      _projectRepository = projectRepository;      
      _userRepository = userRepository;
    }
   
    public Project Project
    {
      get
      {
        HttpCookie httpCookie = HttpContext.Current.Request.Cookies[CurrentProjectId];
        if (httpCookie == null)
        {
          throw new ProjectNotSelectedException();
        }

        Project project = _projectRepository.Get(Convert.ToInt32(httpCookie.Value));         
        if(project == null)
        {
          return null;
        }
        if(project.Users.FirstOrDefault(f=>f.UserName.ToLower() == HttpContext.Current.User.Identity.Name.ToLower()) == null)
        {
          return null;
        }
        return project;
      }      
    }

    public bool IsProjectSelected
    {
      get
      {
        HttpCookie httpCookie = HttpContext.Current.Request.Cookies[CurrentProjectId];
        if (httpCookie == null || httpCookie.Value == string.Empty)
        {
          return false;
        }
        Project project = _projectRepository.Get(Convert.ToInt32(httpCookie.Value));
        if(project == null)
        {
          return false;
        }
        if (project.Users.FirstOrDefault(f => f.UserName.ToLower() == HttpContext.Current.User.Identity.Name.ToLower()) == null)
        {
          HttpContext.Current.Response.Cookies.Remove(CurrentProjectId);
          return false;
        }
        return true;        
      }
    }  
      
    public IBackLink BackLink
    {
      get
      {
        if (System.Web.HttpContext.Current.Session[BackLinkConst] == null)
        {
          System.Web.HttpContext.Current.Session[BackLinkConst] = new BackLink();
        }

        return (IBackLink) (HttpContext.Current.Session[BackLinkConst]);       
      }
    }

    public User User
    {
      get
      {
        return _userRepository.GetByUserName(HttpContext.Current.User.Identity.Name);
      }
    }   
  }
}